package cn.ctbu.xiaopeng.studentscoremanage.service;

import cn.ctbu.xiaopeng.studentscoremanage.anno.Log;
import cn.ctbu.xiaopeng.studentscoremanage.dao.OperateLogRepository;
import cn.ctbu.xiaopeng.studentscoremanage.pojo.dto.OperateLogDTO;
import cn.ctbu.xiaopeng.studentscoremanage.pojo.entity.OperateLog;
import cn.ctbu.xiaopeng.studentscoremanage.pojo.entity.Student;
import cn.ctbu.xiaopeng.studentscoremanage.pojo.vo.OperateLogVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * @author xiaopeng
 * @version 1.0
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class OperateLogService {

    private final OperateLogRepository operateLogRepository;


    /**
     * 分页查询
     *
     * @param pageable
     * @return
     */
    @Log
    public Page<OperateLog> getAllWithPage(Pageable pageable) {
        return operateLogRepository.findAll(pageable);
    }

    /**
     * 分页查询
     *
     * @param example
     * @param pageable
     * @return
     */
    @Log
    public Page<OperateLog> getAllWithPage(Example<OperateLog> example, Pageable pageable) {
        return operateLogRepository.findAll(example, pageable);
    }

    /**
     * 根据条件查询操作日志
     *
     * @param operateLogDTO
     * @param pageable
     * @return
     */
    public Page<OperateLogVO> getOperateLogsByConditions(OperateLogDTO operateLogDTO,
                                                         LocalDateTime operateTimeBegin,
                                                         LocalDateTime operateTimeEnd,
                                                         Pageable pageable) {
        return operateLogRepository.getOperateLogsByConditions(operateLogDTO,operateTimeBegin, operateTimeEnd, pageable);
    }


    // 每三天的午夜 12 点执行
    @Scheduled(cron = "0 0 0 */3 * ?")  // cron 表达式，每三天执行一次，午夜 12 点
    @Transactional
    public void deleteEarliest100Logs() {
        operateLogRepository.deleteEarliest100Logs();
        //获取当前时间
        LocalDateTime now = LocalDateTime.now();
        log.info(now + ":删除了前 100 条操作日志");
    }


    //    @Scheduled(cron = "*/10 * * * * ?")
    @Transactional
    public void deleteEarliest5Logs() {
        operateLogRepository.deleteEarliest100Logs();
        //获取当前时间
        LocalDateTime now = LocalDateTime.now();
        log.info(now + ":删除了前 5 条操作日志");
    }
}
